using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using System.Reflection;
using System.Windows;

namespace OrbitOne.CRMLyncInfoDashboard.PartCatalogs
{

    public class XapNamespaceCatalog: ComposablePartCatalog
    {
        private readonly string m_namespaceName;

        public XapNamespaceCatalog(string namespaceName)
        {
            m_namespaceName = namespaceName;
        }

        private IEnumerable<Assembly> GetAssemblies()
        {
            return Deployment.Current.Parts
                .Where(p => p.Source.StartsWith(m_namespaceName))
                .Select(p =>
                        Assembly.Load(string.Format("{0}, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null",
                                                    p.Source.Substring(0, p.Source.IndexOf(".dll")))));
        }

        private IEnumerable<AssemblyCatalog> GetAssemblyCatalogs()
        {
            var assemblies = GetAssemblies();
            var assemblyCatalogs = assemblies.Select(a => new AssemblyCatalog(a));
            return assemblyCatalogs;
        }

        public override IQueryable<ComposablePartDefinition> Parts
        {
            get 
            {
                var assemblyCatalogs = GetAssemblyCatalogs();
                var parts = assemblyCatalogs.SelectMany(ac => ac.Parts).AsQueryable();
                return parts;
            }
        }
    }
}